<template>
  <div class="properties-content">
    <div class="properties-body" v-if="formConfig.currentItem">
      <Empty class="hint-box" v-if="!formConfig.currentItem.field" description="未选择组件" />

      <Form
        v-else
        ref="formComponentPropsRef"
        :colon="false"
        label-align="left"
        layout="horizontal"
        :model="formConfig.currentItem.componentProps"
        :labelCol="{ style: { width: '92px', color: '#333', fontWeight: '600' } }"
      >
        <div v-if="formConfig.currentItem && formConfig.currentItem.componentProps">
          <FormItem
            v-for="item in inputOptions"
            :name="item.name"
            :key="item.name"
            :label="item.label"
          >
            <!--     处理数组属性，placeholder       -->

            <div v-if="item.children">
              <component
                v-for="(child, index) of item.children"
                :key="index"
                v-bind="
                  isFunction(child.componentProps)
                    ? child.componentProps({
                        record: formConfig.currentItem,
                      })
                    : child.componentProps
                "
                :is="child.component"
                v-model:value="formConfig.currentItem.componentProps[item.name][index]"
                v-model:checked="formConfig.currentItem.componentProps[item.name][index]"
              />
            </div>
            <!--     如果不是数组，则正常处理属性值       -->
            <component
              v-else
              class="component-prop"
              v-bind="
                isFunction(item.componentProps)
                  ? item.componentProps({
                      record: formConfig.currentItem,
                    })
                  : item.componentProps
              "
              :is="item.component"
              v-model:value="formConfig.currentItem.componentProps[item.name]"
              v-model:checked="formConfig.currentItem.componentProps[item.name]"
            />
          </FormItem>
          <FormItem
            label="关联字段"
            v-if="['ApiSelect'].includes(formConfig.currentItem.component)"
          >
            <Select
              placeholder="请选择关联字段"
              mode="multiple"
              v-model:value="formConfig.currentItem.componentProps['linkFields']"
              :options="linkOptions"
            />
          </FormItem>
          <!-- </Row> -->
          <FormItem label="控制属性" v-if="controlOptions.length">
            <Col v-for="item in controlOptions" :key="item.name">
              <Checkbox
                v-if="showControlAttrs(item.includes)"
                v-model:checked="formConfig.currentItem.componentProps[item.name]"
                v-bind="
                  isFunction(item.componentProps)
                    ? item.componentProps({
                        record: formConfig.currentItem,
                      })
                    : item.componentProps
                "
              >
                {{ item.label }}
              </Checkbox>
            </Col>
          </FormItem>
        </div>

        <FormItem label="栅格" v-if="['Grid'].includes(formConfig.currentItem.component)">
          <FormOptions />
        </FormItem>
      </Form>
    </div>
  </div>
</template>
<script lang="ts">
  import {
    Input,
    Form,
    FormItem,
    Switch,
    Checkbox,
    Select,
    InputNumber,
    RadioGroup,
  } from 'ant-design-vue';
  import { ApiSelect } from '/@/components/Form/index';
  import HEmpty from '/@/components/HEmpty/index.vue';
  import RadioButtonGroup from '/@/components/Form/src/components/RadioButtonGroup.vue';

  import { isFunction } from '/@/utils/is';

  import { Col, Row } from 'ant-design-vue';
  import { computed, defineComponent, ref, watch } from 'vue';

  import { useFormDesignStoreWithOut } from '/@/store/modules/formDesign';

  import { useFormDesignState } from '../../../hooks/useFormDesignState';
  import {
    baseComponentControlAttrs,
    baseComponentAttrs,
    baseComponentCommonAttrs,
    componentPropsFuncs,
  } from '../../VFormDesign/config/componentPropsConfig';

  import FormOptions from './FormOptions.vue';

  // import { formItemsForEach, remove } from '../../../utils';
  import { IBaseFormAttrs } from '../config/formItemPropsConfig';

  const dataSourceComps = [
    'ApiSelect',
    'CheckboxGroup',
    'RadioGroup',
    'ApiTreeSelect',
    'Upload',
    'Cascader',
  ];

  export default defineComponent({
    name: 'ComponentProps',
    components: {
      FormOptions,
      Empty: HEmpty,
      Input,
      Form,
      FormItem,
      Switch,
      Checkbox,
      Select,
      InputNumber,
      RadioGroup,
      RadioButtonGroup,
      Col,
      Row,
      ApiSelect,
    },
    setup() {
      // 让compuated属性自动更新
      // const dummyUpdate = ref(0);
      const formDesignStore = useFormDesignStoreWithOut();
      const formComponentPropsRef = ref();
      watch(formComponentPropsRef, () => {
        formDesignStore.setFormComponentPropsRef(formComponentPropsRef);
      });
      const allOptions = ref([] as Omit<IBaseFormAttrs, 'tag'>[]);
      const showControlAttrs = (includes: string[] | undefined) => {
        if (!includes) return true;
        return includes.includes(formConfig.value.currentItem!.component);
      };

      const { formConfig, client } = useFormDesignState();

      if (formConfig.value.currentItem) {
        formConfig.value.currentItem.componentProps =
          formConfig.value.currentItem.componentProps || {};
      }

      // watch(
      //   () => formConfig.value.currentItem?.field,
      //   (_newValue, oldValue) => {
      //     formConfig.value.schemas &&
      //       formItemsForEach(formConfig.value.schemas, (item) => {
      //         const link = item.componentProps!.linkFields;
      //         if (link) {
      //           console.log(
      //             '%c_newValue, oldValue===>183： ',
      //             'background: rgb(23, 197, 237,.6); color: #ff5023; font-size:18px;font-weight:700',
      //             _newValue,
      //             oldValue,
      //             link,
      //           );

      //           const index = link.findIndex((linkItem) => linkItem === oldValue);
      //           index !== -1 && remove(link, index);
      //         }
      //       });
      //   },
      // );

      watch(
        () => formConfig.value.currentItem && formConfig.value.currentItem.component,
        () => {
          allOptions.value = [];
          baseComponentControlAttrs.forEach((item) => {
            item.category = 'control';
            if (!item.includes) {
              // 如果属性没有include，所有的控件都适用

              allOptions.value.push(item);
            } else if (item.includes.includes(formConfig.value.currentItem!.component)) {
              // 如果有include，检查是否包含了当前控件类型
              allOptions.value.push(item);
            }
          });

          baseComponentAttrs[formConfig.value.currentItem!.component] &&
            baseComponentAttrs[formConfig.value.currentItem!.component].forEach(async (item) => {
              if (item.component) {
                if (['Switch', 'Checkbox', 'Radio'].includes(item.component)) {
                  item.category = 'control';
                  allOptions.value.push(item);
                } else {
                  item.category = 'input';
                  allOptions.value.push(item);
                }
              }
            });

          baseComponentCommonAttrs.forEach((item) => {
            item.category = 'input';
            if (item.includes) {
              if (item.includes.includes(formConfig.value.currentItem!.component)) {
                allOptions.value.push(item);
              }
            } else if (item.exclude) {
              if (!item.exclude.includes(formConfig.value.currentItem!.component)) {
                allOptions.value.push(item);
              }
            } else {
              allOptions.value.push(item);
            }
          });
        },
        {
          immediate: true,
        },
      );
      // 控制性的选项
      const controlOptions = computed(() => {
        return allOptions.value.filter((item) => {
          return item.category == 'control';
        });
      });

      // 非控制性选择
      const inputOptions = computed(() => {
        return allOptions.value.filter((item) => {
          return item.category == 'input';
        });
      });

      watch(
        () => formConfig.value.currentItem!.componentProps,
        () => {
          const func = componentPropsFuncs[formConfig.value.currentItem!.component];
          if (func) {
            func(formConfig.value.currentItem!.componentProps, allOptions.value);
          }
        },
        {
          immediate: true,
          deep: true,
        },
      );
      const linkOptions = computed(() => {
        return (
          formConfig.value.schemas[client.value] &&
          formConfig.value.schemas[client.value]
            .filter((item) => item.field !== formConfig.value.currentItem!.field)
            .map(({ label, field }) => ({ label: label + '/' + field, value: field }))
        );
      });

      return {
        dataSourceComps,
        formComponentPropsRef,
        formConfig,
        showControlAttrs,
        linkOptions,
        controlOptions,
        inputOptions,
        isFunction,
      };
    },
  });
</script>
